﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web;

namespace XSTDZ.ERP.Infrastructure.Exceptions
{
    /// <summary>
    /// 全局异常处理
    /// </summary>
   public  class CustomException:FilterAttribute,IExceptionFilter 
    {
       public void OnException(ExceptionContext filterContext)
       {
           if (filterContext.ExceptionHandled == true)
           {
               HttpException httpExcec = filterContext.Exception as HttpException;
               if (httpExcec.GetHttpCode() != 500)//为什么要特别强调500 因为MVC处理HttpException的时候，如果为500 则会自动     //将其ExceptionHandled设置为true，那么我们就无法捕获异常
                {
                    return;
                }
           }
           HttpException httpException = filterContext.Exception as HttpException;
           if (httpException != null)
           {
               filterContext.Controller.ViewBag.UrlRefer = filterContext.HttpContext.Request.UrlReferrer;
               if (httpException.GetHttpCode() == 404)
                 {
                     filterContext.HttpContext.Response.Redirect("~/Home/Exception?error=资源不存在！");
                 }
                 else if (httpException.GetHttpCode() == 500)
                 {
                     filterContext.HttpContext.Response.Redirect("~/Home/Exception?error=内部异常错误！");
                 }
             
           }

       
           //写入日志 记录

           filterContext.ExceptionHandled = true;//设置异常已经处理
       }
    }
}
